// pages/create/create.ts
const api = require('../../utils/api');
const util = require('../../utils/common');

Page({
  data: {
    formats: {},
    placeholder: '开始输入...',
    keyboardHeight: 0,
    title: '',
    content: '',
    author: '',
  },
  onChange (e) {
    // 标题
    this.setData({
      title: e.detail.value
    })
  },
  oninput(e) {
    // 获取输入内容
    this.setData({
      content: e.detail.html
    })
  },
  onAdd () {
    const {title, content} = this.data;
    if (title && content) {
      let that = this;
      wx.showModal({
        title: '您确定要发布文章吗？',
        success (res) {
          // 用户点击确定
          if (res.confirm) {
            // 文章发布
            api.addArticle({
              title: that.data.title,
              content: that.data.content,
              author: that.data.author,
              categories: '1',
              status: 'publish'
            }).then(res => {
              if (res?.id) {
                wx.navigateTo({
                  url: `/pages/list/list`
                })
              }
            })
          }
        }
      })
    } else {
      const message = !this.data.title? '请输入标题': '请输入文章';
      util.showToast(message);
    }
  },
  onLoad(options) {
    if (options.userId) {
      this.setData({
        author: options.userId
      })
    }
    // 获取键盘高度
    // let that = this;
    // wx.onKeyboardHeightChange(res => {
    //   console.log("keyboardHeight==?", res.height);
    //   // this.onEditor.scrollIntoView();
    //   this.setData({
    //     keyboardHeight: res.height
    //   })
    // })
  },
  onEditorReady() {
    const that = this;
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  onBlur() {
    // 在失焦的时候收起键盘
    this.editorCtx.blur()
  },
  addDivider() {
    this.editorCtx.insertDivider();
  },
  clearFormat() {
    this.editorCtx.clear();
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    console.log('format', name, value);
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail;
    // console.log("formats-->", formats);
    this.setData({ formats })
  },
  clear() {
    this.editorCtx.clear();
  },
  insertImage() {
    const that = this;
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        // res.tempFiles 是选择的文件数组
        api.upload(res.tempFiles).then(files => {
          files.map(item => {
            that.editorCtx.insertImage({
              src: item.url,
              alt: '图片加载错误',
              width: '100%'
            })
          })
        })
      }
    })
  }
})